package com.example.lyqwork.controller;


import com.example.lyqwork.pojo.CarOrder;
import com.example.lyqwork.pojo.ResponseMessage;
import com.example.lyqwork.pojo.dto.CarOrderDto;
import com.example.lyqwork.pojo.dto.CarOrderEditDto;
import com.example.lyqwork.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController //接口方法返回对象 转换成json文本
@RequestMapping("/order")
public class CarOrderController {

    @Autowired
    IOrderService orderService;


    @PostMapping(consumes = "application/json")
    public ResponseMessage add(@Validated @RequestBody CarOrderDto orderDto){
        CarOrder order = orderService.add(orderDto);
        return ResponseMessage.success(order);
    }


    @GetMapping(value = "/by_user/{userId}")
    public ResponseMessage getOrder(@PathVariable Integer userId){
        List<CarOrder>  res = orderService.getOrder(userId,0,3);
        if (res.equals(new ArrayList<CarOrder>())) {
            return ResponseMessage.error("暂无订单");
        }

        return ResponseMessage.success(res);
    }

    @GetMapping(value = "/by_order/{orderId}")
    public ResponseMessage getOrderByOrderId(@PathVariable Integer orderId){
        List<CarOrder>  res = orderService.getOrderByOrderId(orderId);
        if (res.equals(new ArrayList<CarOrder>())) {
            return ResponseMessage.error("暂无订单");
        }
        return ResponseMessage.success(res);
    }

    @DeleteMapping(value = "/del_by_order/{orderId}")
    public ResponseMessage deleted(@PathVariable Integer orderId){
        orderService.deleted(orderId);
        return ResponseMessage.success("删除成功");
    }

    @PutMapping(consumes = "application/json")
    public ResponseMessage update(@Validated @RequestBody CarOrderEditDto orderDto){
        CarOrder carOrer = orderService.getOrderByOrderId(orderDto.getOrderId()).get(0);
        String[] dataList = carOrer.getDataStr().split(",");
        String[] stateList = carOrer.getDataStatus().split(",");
        for (int i = 0; i < dataList.length; i++) {
            if (dataList[i].equals(orderDto.getEditName())) {
                stateList[i] =orderDto.getEditValue();
            }
        }
        carOrer.setDataStatus(String.join(",",stateList));
        CarOrder order = orderService.update(carOrer);
        return ResponseMessage.success(order);
    }

}
